<!-- 横向选项卡（水平滚动导航栏） -->
<template>
  <scroll-view
    class="container-scroll"
    scroll-y
    lower-threshold="50"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    scroll-with-animation
    refresher-enabled
  >
    <!-- 顶部导航栏 -->
    <view class="horizonal-tab">
      <view class="scroll-tab">
        <block v-for="(item, index) in tabBars" :key="index">
          <view
            class="scroll-tab-item"
            :class="{ active: tabIndex == index }"
            @tap="isTriggered ? null : toggleTab(index)"
          >
            {{ item.name }}
            <view class="scroll-tab-line"></view>
          </view>
        </block>
      </view>
      <!-- 地址选择组件 -->
      <StAddress @change="change">
        <view class="address">
          <uni-icons type="location" color="#666" size="24" />
          <span class="address-text">
            {{
              addressInfo.province == ""
                ? `请选择区域`
                : addressInfo.province + addressInfo.city + addressInfo.area
            }}
          </span>
        </view>
      </StAddress>
    </view>

    <!-- 内容区 -->
    <view class="content">
      <!-- 内容列表区域 -->
      <view class="content-list">
        <view
          class="content-item"
          v-for="(item, index) in contentList[tabIndex].data"
          :key="index"
          @tap="isTriggered ? null : toDetail(item.id, item.type)"
        >
          <view class="content-item-title">{{ item.name }}</view>
          <view class="content-item-image"
            ><image
              :src="img.imgUrl"
              v-for="(img, index) in item.media"
              :key="index"
              mode="scaleToFill"
          /></view>
          <view class="content-item-note">{{ item.introduction }}</view>
          <view class="content-item-time">2024-03-07 12:00:00</view>
        </view>
      </view>
      <uni-load-more :status="moreStatus"></uni-load-more>
    </view>
  </scroll-view>
</template>

<script lang="ts" setup>
import { getCategoryDataAPI } from "@/services";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
const urlBase = "http://localhost:3333/public/uploads/";

// 加载更多状态
let moreStatus = ref<UniHelper.UniLoadMoreStatus>("more");
// tab栏索引
const tabIndex = ref(0);
// 内容区
const contentList = reactive<any>([
  { type: "美食", data: [] },
  { type: "旅游", data: [] },
]);
// tab栏
const tabBars = ref([
  {
    name: "美食餐厅",
    id: "food",
  },
  {
    name: "旅游景点",
    id: "travel",
  },
]);
let marginTop = ref("");
let scrollH = ref(0);
// 是否触发下拉刷新
let isTriggered = ref(false);

// 地址信息
let addressInfo = ref({
  province: "",
  city: "",
  area: "",
});
// 初始化地址信息
const initAddressInfo = () => {
  addressInfo.value = {
    province: "",
    city: "",
    area: "",
  };
};
let pageParams = {
  page: 1,
  size: 3,
};
// 初始化页面数据
const initContentData = async () => {
  const location =
    addressInfo.value.province +
    addressInfo.value.city +
    addressInfo.value.area;
  pageParams.page = 1;
  const type = tabIndex.value == 0 ? "food" : "travel";
  let result: any = await getCategoryDataAPI(
    type,
    location,
    pageParams.size,
    pageParams.page
  );
  console.log(result);
  if (result.code == 200) {
    contentList[tabIndex.value].data = result.data;
    if (pageParams.page < result.pages) {
      pageParams.page++;
      moreStatus.value = "more";
    } else {
      moreStatus.value = "noMore";
    }
  } else {
    contentList[tabIndex.value].data = result.data;
    uni.showToast({
      title: "暂无数据",
      icon: "none",
    });
    moreStatus.value = "noMore";
  }
};
// 获取scroll-view高度
const getScrollHeight = () => {
  let sys = uni.getSystemInfoSync();
  let winWidth = sys.windowWidth;
  let winrate = 750 / winWidth;
  scrollH.value = sys.windowHeight * winrate;
};

const onRefresherrefresh = async () => {
  isTriggered.value = true;
  await initContentData().then(() => {
    isTriggered.value = false;
  });
};

// 页面加载时初始化地址信息
onLoad(() => {
  initAddressInfo();
  initContentData();
  getScrollHeight();
});
onShow(() => {
  //.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
  uni
    .createSelectorQuery()
    .select(".horizonal-tab")
    .boundingClientRect((e: any) => {
      marginTop.value = e.height + "px";
    })
    .exec();
});
// 返回顶部
const toTop = () => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  });
};
// tab切换
const toggleTab = (index: number) => {
  tabIndex.value = index;
  toTop();
  initContentData();
};
// 地址选择组件回调
const change = (e: any) => {
  toTop();
  addressInfo.value = e;
  initContentData();
};
// 下拉加载更多
let onScrollToLower = async () => {
  if (moreStatus.value == "noMore") {
    return uni.showToast({
      title: "没有更多了",
      icon: "error" || "fail",
    });
  }
  const location =
    addressInfo.value.province +
    addressInfo.value.city +
    addressInfo.value.area;
  const type = tabIndex.value == 0 ? "food" : "travel";
  moreStatus.value = "loading";
  let result: any = await getCategoryDataAPI(
    type,
    location,
    pageParams.size,
    pageParams.page
  );

  if (result.code == 200) {
    contentList[tabIndex.value].data.push(...result.data);

    if (pageParams.page < result.pages) {
      pageParams.page++;
      moreStatus.value = "more";
    } else {
      moreStatus.value = "noMore";
    }
  } else {
    uni.showToast({
      title: "获取数据失败",
      icon: "none",
    });
    moreStatus.value = "noMore";
  }
};

const toDetail = (id: number, type: string) => {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${id}&type=${type}`,
  });
};
</script>

<style lang="scss">
.container-scroll {
  height: calc(100vh - var(--window-top));

  .horizonal-tab {
    background-color: #f7f7f7;
    .active {
      color: #ffa500;
      background-color: #fff;
      .scroll-tab-line {
        position: absolute;
        bottom: 17%;
        left: 34%;
        border-bottom: 5rpx solid #ffa500;
        border-top: 5rpx solid #ffa500;
        border-radius: 20rpx;
        width: 80rpx;
      }
    }
    .address {
      border: 15rpx solid #fff;
      border-radius: 0 0 10rpx 10rpx;
      box-sizing: border-box;
      background-color: #eee;
      height: 80rpx;
      font-size: 26rpx;
      line-height: 40rpx;
      position: relative;
      uni-icons {
        position: absolute;
        top: 10rpx;
        margin-left: 10rpx;
      }
      .address-text {
        position: absolute;
        top: 10rpx;
        left: 60rpx;
        color: #666;
      }
    }
  }
  .scroll-tab {
    white-space: nowrap; /* 必要，导航栏才能横向*/
    border-bottom: 1rpx solid #ddd;
    height: 80rpx;
    text-align: center;
    .scroll-tab-item {
      display: inline-block; /* 必要，导航栏才能横向*/
      width: 49%;
      line-height: 80rpx;
      position: relative;

      /* margin: 20rpx 30rpx 0 30rpx; */
    }
    .scroll-tab-item:first-child {
      border-right: 1rpx solid #ddd;
    }
  }
  .content {
    height: calc(100vh - var(--window-top));
    .content-list {
      .content-item {
        padding: 20rpx;
        background-color: white;
        border-bottom: 1rpx solid #ddd;
      }
      .content-item-title {
        font-size: 32rpx;
        font-weight: bold;
        padding-bottom: 10rpx;
      }
      .content-item-image {
        height: 200rpx;
        display: flex;
        image {
          flex: 1;
          height: 100%;
          border-radius: 5%;
          padding: 0 5rpx;
          max-width: 33%;
        }
      }
      .content-item-note {
        white-space: nowrap; /* 禁止换行 */
        overflow: hidden; /* 隐藏超出容器的内容 */
        text-overflow: ellipsis; /* 使用省略号代替超出部分的文本 */
      }
      .content-item-time {
        font-size: 24rpx;
        color: #666;
        text-align: right;
      }
    }
  }
}
</style>
